const Model = require('../models/group-model')
const OrderModel = require('../models/order-model')
const ResponseModel = require('../models/response-model')

module.exports = {

    // 查询
    'get::/group/list': async function(ctx) {

        const { deviceId } = ctx.request.query
        
        const whereBuilder = countQuery => {
            if (deviceId) {
                countQuery.where('device_id', deviceId)
            }
        }
        const list = await Model.list(Model.buildPaging(ctx.request.query), whereBuilder)
        ctx.response.body = ResponseModel.success(list)
    },
    // 保存
    'post::/group/save': async function(ctx) {

        const model = ctx.request.body

        if (model.id) {
            const updated = await Model.updateBy({
                name: model.name
            }, { id: model.id })
        } else {
            const inserted = await Model.insert(model)
            if (inserted && inserted.length > 0) {
                id = inserted[0]
                model.id = inserted[0]
            }
        }

        ctx.response.body = ResponseModel.success()
    },
    // 删除
    'get::/group/delete/:id': async function(ctx) {

        const { id } = ctx.request.params
        if (id) {
            const deleted = await Model.delete({ id: id })
            if (deleted) {
                await OrderModel.delete({'group_id': id})
            }
        }
        ctx.response.body = ResponseModel.success()
    },
    // 选项
    'get::/group/options': async function(ctx) {

        const params = ctx.request.query

        const list = await Model.list(Model.buildPaging(params))

        ctx.response.body = ResponseModel.success(list)
    }
}
  